package com.google.code.dajly.view;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.net.MalformedURLException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableModel;

import com.google.code.dajly.model.*;

public class GUI implements Observer{
	
	   private Model _m;
       private JFrame mainWindow;
       private JPanel controlPanel;
       private Feed currentFeed;
	   private Entry currentEntry;
	   private TableModel tableModel;
//	   private String filterText;
	   private JTextField filterStrField;
	   private ListModel listModel;
	   private JList list;
	   private JTable feedTable;
	   private JEditorPane messageTextArea;
	   private JLabel feedInfo;




	   public GUI(){
		   
			_m = new Model();
			_m.addObserver(this);
			
			
//			try {
//				
//
//				_m.addFeed("http://www.repubblica.it/rss/homepage/rss2.0.xml");
//				_m.addFeed("http://www.pigoz.eu/rss2e.xml");
//				_m.addFeed("http://www.poliziadistato.it/pds/ipol/ipol_rss.xml");
//				
//
//				
//			} catch (MalformedURLException e) {
//				System.out.println("inserisci un URL valido # " + e.getMessage());
//			}
//			try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}
//			catch (Exception e) { }

			
			mainWindow=new JFrame("dajly");
			mainWindow.addWindowListener(new WindowListener(){

				public void windowActivated(WindowEvent e) {}
				public void windowClosed(WindowEvent e) {
					System.out.println("Sending termination signal");
					System.exit(0);
				}
				public void windowClosing(WindowEvent e) {
					System.out.println("Saving Model");
					_m.saveModel();
					System.out.println("Closing Window");
					mainWindow.dispose();
				}
				public void windowDeactivated(WindowEvent e) {}
				public void windowDeiconified(WindowEvent e) {}
				public void windowIconified(WindowEvent e) {}
				public void windowOpened(WindowEvent e) {}
				
			});
			mainWindow.setSize(800,620);
			mainWindow.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

			
			controlPanel = new JPanel();

			
			//menu bar
			JMenuBar menuBar = new JMenuBar();
			mainWindow.setJMenuBar(menuBar);
			JMenu fileMenu = new JMenu("File");
			JMenu editMenu = new JMenu("Modifica");
			menuBar.add(fileMenu);
			//file element
			JMenuItem exitItem = new JMenuItem("Esci");
			exitItem.addActionListener(
					new ActionListener(){

				public void actionPerformed(ActionEvent event)
			      {
			         
			         System.exit(0);
			      }
			   });
			
			fileMenu.add(exitItem);
			menuBar.add(editMenu);
			//modifica elements
			JMenu prefItem = new JMenu("Preferenze");
			editMenu.add(prefItem);
			JMenuItem impItem = new JMenuItem("Imposta Timer");
			prefItem.add(impItem);
			impItem.addActionListener(
				    new ActionListener(){

					public void actionPerformed(ActionEvent event)
				      {
				         
						impTimer();
				      }
				   });
			JMenuItem addFeedItem = new JMenuItem("Aggiungi feed");
			addFeedItem.addActionListener(
				    new ActionListener(){

					public void actionPerformed(ActionEvent event)
				      {
				         
						addFeed();
				      }
				   });
			editMenu.add(addFeedItem);
			
			
			//control panel el
			controlPanel.add(new JLabel("Ricerca"));
			filterStrField=new JTextField(20);

			controlPanel.add(filterStrField);

			JButton filterButton = new JButton("Filtra");
			filterButton.addActionListener(
			    new ActionListener(){

				public void actionPerformed(ActionEvent event)
			      {
			         
					filtra();
			      }
			   });
			controlPanel.add(filterButton);
			
			JButton refButton = new JButton("Aggiorna");
			refButton.addActionListener(
				new ActionListener(){

				public void actionPerformed(ActionEvent event)
			      {
			         
					System.out.println("refresh");
					_m.resetTimer();
					_m.refreshFeeds();
					_m.startTimer();
			      }
			   });
			controlPanel.add(refButton);
			

			
			//feed panel el
			makeListModel();
			list = new JList(listModel);
			list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			list.addListSelectionListener(new ListSelectionListener(){

				public void valueChanged(ListSelectionEvent e) {
					if(e.getValueIsAdjusting() == false){
						
						System.out.println("listselectionchanged "+list.getSelectedValue().toString());
						currentFeed = _m.getFeedByTitle(list.getSelectedValue().toString());
						
						makeTableModel();
						feedTable.setModel(tableModel);
						feedTable.setDefaultRenderer(Object.class, new MyCellRenderer(_m,currentFeed));
						feedTable.getColumnModel().getColumn(0).setPreferredWidth(300);
						feedTable.getColumnModel().getColumn(1).setPreferredWidth(100);
						
	                    String _infotext = "<html><b>"+currentFeed.getTitle()+"</b><br>";
	                    if(currentFeed.hasLocation()){
	                    	_infotext += "<b>Locations:</b>";
	                    	boolean _first = true;
	                    	for(String _b : currentFeed.getLocations()){
	                    		_infotext += _first?" "+_b:", "+_b;
	                    		if(_first)
	                    			_first = false;
	                    	}
	                    }
	                    if(currentFeed.hasBusiness()){
	                    	if(currentFeed.hasLocation())
	                    		_infotext += "<br>";
	                    	_infotext += "<b>Businesses:</b>";
	                    	boolean _first = true;
	                    	for(String _b : currentFeed.getBusinesses()){
	                    		_infotext += _first?" "+_b:", "+_b;
	                    		if(_first)
	                    			_first = false;
	                    	}
	                    }
	                    _infotext += "</html>";
	                    feedInfo.setText(_infotext);
						
					}
				}
				
			});

			list.addMouseListener(new MouseListener(){
				public void mouseClicked(MouseEvent e) { 

					if(SwingUtilities.isRightMouseButton(e))
					    {
						JPopupMenu popup = new JPopupMenu();
						JMenuItem item = new JMenuItem("Elimina");
						item.addActionListener(
								new ActionListener(){

									public void actionPerformed(ActionEvent event)
								      {
					                        _m.deleteFeed(currentFeed.getURL().toString());
								      }
								   }
								);
						popup.add(item);
						popup.show(e.getComponent(),e.getX(), e.getY());

					    }
                     }

				public void mouseEntered(MouseEvent e) {
					// TODO Auto-generated method stub
					
				}


				public void mouseExited(MouseEvent e) {
					// TODO Auto-generated method stub
					
				}


				public void mousePressed(MouseEvent e) {
					// TODO Auto-generated method stub
					
				}

				public void mouseReleased(MouseEvent e) {
					// TODO Auto-generated method stub
					
				}
	       		 } );
		    
		    
			JScrollPane feedScPanel = new JScrollPane(list,
					JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
					JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
			
			
			
			JPanel feedSubPanel=new JPanel();
			JButton deleteButton = new JButton("Elimina il Feed selezionato");
			deleteButton.addActionListener(
				new ActionListener(){

				public void actionPerformed(ActionEvent event)
			      {
                        _m.deleteFeed(currentFeed.getURL().toString());
			      }
			   });
			feedSubPanel.add(deleteButton);
			JSplitPane subSplitPane0 = new JSplitPane(JSplitPane.VERTICAL_SPLIT,feedScPanel,feedSubPanel);
			subSplitPane0.setDividerLocation(465);
			//messPanel elem

			makeTableModel();
			feedTable = new JTable(tableModel);
			
			
			feedTable.getColumnModel().getColumn(0).setPreferredWidth(300);
			feedTable.getColumnModel().getColumn(1).setPreferredWidth(100);
			feedTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			feedTable.setDefaultRenderer(Object.class, new MyCellRenderer(_m,currentFeed));
			ListSelectionModel sM =  feedTable.getSelectionModel();
			sM.addListSelectionListener(new ListSelectionListener() {
	            public void valueChanged(ListSelectionEvent e) {
	                //Ignore extra messages.
	                if (e.getValueIsAdjusting()) return;

	                ListSelectionModel lsm = (ListSelectionModel)e.getSource();
	                if (lsm.isSelectionEmpty()) {
	                    System.out.println("No rows are selected.");
	                } else {
	                    int selectedRow = lsm.getMinSelectionIndex();
	                    System.out.println("Row " + selectedRow
	                                       + " is now selected.");
	                    currentEntry = currentFeed.getEntries().get(selectedRow);
	                    _m.setRead(currentEntry);
	                    messageTextArea.setText("<html>"+currentEntry.getMessage()+"</html>");
//	                    storyTitle.setText(currentEntry.getTitle());
	                                
	                }
	            }
	        });
			feedTable.addMouseListener(new MouseListener(){
				public void mouseClicked(MouseEvent e) { 

					if(SwingUtilities.isRightMouseButton(e))
					    {
						JPopupMenu popup = new JPopupMenu();
						JMenuItem item = new JMenuItem("Vai alla pagina");
						item.addActionListener(
								new ActionListener(){

									public void actionPerformed(ActionEvent event)
								      {
										openNativeBrowser(currentEntry.getStoryURL().toString());
								      }
								   }
								);
						popup.add(item);
						popup.show(e.getComponent(),e.getX(), e.getY());

					    }
                     }

				public void mouseEntered(MouseEvent e) {
					// TODO Auto-generated method stub
					
				}

				public void mouseExited(MouseEvent e) {
					// TODO Auto-generated method stub
					
				}

				public void mousePressed(MouseEvent e) {
					// TODO Auto-generated method stub
					
				}


				public void mouseReleased(MouseEvent e) {
					// TODO Auto-generated method stub
					
				}
	       		 } );
			
			feedInfo = new JLabel("<html><b>Titolo<br>Location: </b>N/A <br><b>Business: </b>N/A");
			
			
		    		
			JScrollPane messScPanel = new JScrollPane(feedTable,
					JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
					JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
			
			JSplitPane _splitFeed = new JSplitPane(JSplitPane.VERTICAL_SPLIT, feedInfo,messScPanel);


			
			//messInfoPanel elem
			messageTextArea = new JEditorPane();
			messageTextArea.setEditable(false);
			messageTextArea.setContentType("text/html");
			


			JScrollPane messInfoScPanel = new JScrollPane(messageTextArea,
				    JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
					JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
			
			JButton visitButton = new JButton("visita URL");
			visitButton.addActionListener(
				new ActionListener(){

				public void actionPerformed(ActionEvent event)
			      {
			         //da impl
					System.out.println("visita il sito");
					openNativeBrowser(currentEntry.getStoryURL().toString());
			      }
			   });
			JPanel subPanel=new JPanel();
			subPanel.add(visitButton);
			//Da impl
			
			
			JSplitPane subSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,messInfoScPanel,subPanel);
			subSplitPane.setDividerLocation(160);
			JSplitPane eastSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,_splitFeed,subSplitPane);
			eastSplitPane.setDividerLocation(300);
			JSplitPane southSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,subSplitPane0,eastSplitPane);
			JSplitPane mainSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, controlPanel, southSplitPane);
			mainWindow.add(mainSplitPane);
			
			
			mainWindow.setVisible(true);
			
	        }
	  
	   
	   
	   
	   
	   
	   
	   
	   
	   
	   
	   
	   
	   
	   
	   
	   
	   public static void main(String[] args) {
			try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}
			catch (Exception e) { }
			new GUI();
		}



		public void update(Observable o1, Object o2) {
			
			System.out.println("ricevuto un update da: "+o1+" - argomento: "+o2 );
			
			if(o2 instanceof String )
				if(((String)o2).equals("deletedFeed")){
					makeListModel();
					list.repaint();
				}
			if(o2 instanceof String )
				if(((String)o2).equals("addFeed")){
					makeListModel();
					list.repaint();
				}
			if(o2 instanceof String)
				if(((String)o2).equals("refreshFeed")){
					makeListModel();
					list.repaint();
				}
			
		}
		
		private void makeTableModel(){
			
			if (currentFeed != null){
				tableModel = new AbstractTableModel(){

					private static final long serialVersionUID = 1L;

					private String[] columnNames ={"Titolo","Data"};
					
					private Format formatter = new SimpleDateFormat("E, dd MMM HH:mm:ss");
					
					public String getColumnName(int col) {
				        return columnNames[col];
				    }
					
					public int getColumnCount() {
						return 2; // titolo + descrizione
					}

					public int getRowCount() {
						return currentFeed.getEntries().size(); 
						//numero di entries per il feed corrente
					}

					public Object getValueAt(int rowIndex, int columnIndex) {
						switch (columnIndex) {
						case 0:
							return currentFeed.getEntries().get(rowIndex).getTitle();

						case 1:
							return formatter.format(currentFeed.getEntries().get(rowIndex).getPublishedDate());

						default:
							break;
						}
						return null;
					}

					public boolean isCellEditable(int row, int col)
					{ return false; }
				};
			} else {
				tableModel = new AbstractTableModel(){

					private static final long serialVersionUID = 1L;

                    private String[] columnNames ={"Titolo","Data"};
					
					public String getColumnName(int col) {
				        return columnNames[col];
				    }
					
					public int getColumnCount() {
						return 2; // titolo + descrizione
					}

					public int getRowCount() {
						return 0; 
						//numero di entries per il feed corrente
					}

					public Object getValueAt(int rowIndex, int columnIndex) {
						return null;
					}

					public boolean isCellEditable(int row, int col)
					{ return false; }
				};
			}	
			
		}
		
		private void makeListModel(){
			
			listModel = new AbstractListModel(){

				private static final long serialVersionUID = 1L;

				public Object getElementAt(int index) {
					return _m.getFeeds().get(index).getTitle();
				}

				public int getSize() {
					return _m.getFeeds().size();
				}
				
			};
			
			
		}
		
		private void filtra(){
			_m.setFilter(new FilterType().setType("title").setFilter(filterStrField.getText().trim()));
			makeTableModel();
			feedTable.setModel(tableModel);
			feedTable.setDefaultRenderer(Object.class, new MyCellRenderer(_m,currentFeed));
			System.out.println("asd");
		}
		private void addFeed(){
			
			String s=JOptionPane.showInputDialog("Inserire URL del feed","http://");
         try {
				


              _m.addFeed(s);
				
			} catch (MalformedURLException e) {
				JOptionPane.showMessageDialog(null, "URL non valido", "Errore", JOptionPane.ERROR_MESSAGE);

			}
			try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}
			catch (Exception e) { }
		}
		
	      private void impTimer(){
	    	  String s=JOptionPane.showInputDialog("Inserire lintervallo di tempo di refresh automatico(in millisecondi)");
	    	  int n=Integer.parseInt(s);
	    	  if(n>0){
	    	  _m.setTimerQuantum(n);
	    	  }else{
	    		  JOptionPane.showMessageDialog(null, "Numero inserito non valido", "Errore", JOptionPane.ERROR_MESSAGE);
	           }
	      }
	      
	      
	      private void openNativeBrowser(String url) {
	    	
	    	StringBuffer call = new StringBuffer();
	    	System.err.println(System.getProperty("os.name"));
	    	System.err.println(System.getProperty("user.dir"));

	    	try {
	    	// which OS ?
	    	String operatingSystem = System.getProperty("os.name");
	    	System.out.println(operatingSystem);

	    	// how to call the OS
	    	if (operatingSystem.toLowerCase().indexOf("windows") > -1)
	    	call.append("cmd /c start ").append(url);
	    	else
	    	if (operatingSystem.toLowerCase().indexOf("mac") > -1)
	    	call.append("open -a Safari ").append(url + "");
	    	else if(operatingSystem.toLowerCase().indexOf("linux") > -1)
	    	// use Script 'netscape'
	    	call.append("mozilla ").append(url).append(" &");
	    	else
	    	call.append("netscape ").append(url).append(" &");
	    	System.err.println(call.toString());
	    	// start it ...
	    	Runtime.getRuntime().exec(call.toString());

	    	}
	    	catch (Exception e) {
	    	System.out.println(e.getMessage());
	    	e.printStackTrace();
	    	}
	    	}
		
}

class MyCellRenderer extends DefaultTableCellRenderer{
	private static final long serialVersionUID = 1L;

	private Feed currentFeed;
	private Model _m;

	public MyCellRenderer(Model _m, Feed currentFeed){
		this._m = _m;
		this.currentFeed = currentFeed;
	}

	public Component getTableCellRendererComponent(JTable table, 
			Object value, boolean isSelected, boolean hasFocus, int row, int column) {

		JLabel parent = (JLabel) super.getTableCellRendererComponent(table, 
				value, isSelected, hasFocus, row, column);

		if(!_m.isRead(currentFeed.getEntries().get(row))) 
			parent.setFont(parent.getFont().deriveFont(Font.BOLD));
		return parent;
	}  

}
